import React, {
  useRef,
  useState,
  useEffect,
  useCallback,
  useMemo,
} from 'react';
import { Button, Image, Swiper, List } from 'antd-mobile';
import { SearchOutline } from 'antd-mobile-icons';
import { history } from 'umi';
import { fetchIndex } from '@/services/home';
import GoodsItem from './components/GoodsItem';
import styles from './index.less';

const Home: React.FC = () => {
  const [pageData, setPageData] = useState<any>({});

  useEffect(() => {
    fetchIndex().then((res) => {
      setPageData(res);
    });
  }, []);

  const hanldeClick = useCallback((value) => {
    history.push(value.url);
  }, []);

  const { slides, categories, goods } = pageData;
  const items = useMemo(
    () =>
      slides?.map((item: any) => (
        <Swiper.Item key={item.id}>
          <div onClick={() => hanldeClick(item)}>
            <Image src={item.img_url} />
          </div>
        </Swiper.Item>
      )),
    [pageData],
  );

  const catagorys = useMemo(
    () =>
      categories?.slice(0, 6).map((item: any) => (
        <div className={styles.text} key={item.id}>
          {item.name}
        </div>
      )),
    [pageData],
  );

  const goodsItem = useMemo(
    () =>
      goods?.data.map((item: any) => (
        <GoodsItem
          url={item.cover_url}
          title={item.title}
          price={item.price}
          key={item.id}
        />
      )),
    [pageData],
  );

  const handleSearch = useCallback(() => {
    history.push('/search');
  }, [history]);

  return (
    <div>
      <div className={styles.bynBox}>
        <Button color="primary" block size="middle" onClick={handleSearch}>
          <SearchOutline />搜 索
        </Button>
      </div>
      <Swiper autoplay loop>
        {items}
      </Swiper>
      <div className={styles.catagory}>{catagorys}</div>
      <div className={styles.goodsList}>
        <p className={styles.hot}>热销商品</p>
        {goodsItem}
      </div>
    </div>
  );
};

export default Home;
